$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'production/erporderproduction/yangluolist',
        datatype: "json",
        colModel: [
            {
                label: '打印', width: 55, align: 'center', title: false,
                formatter: function (value, options, row) {
                    var actions = [];
                    actions.push("<a href=\"javascript:;\" onclick=\"return vm.printGoods('" + row.orderNo + "');\">送</a>&nbsp;&nbsp;|");
                    actions.push("<a href=\"javascript:;\" onclick=\"return vm.showEMS('" + row.orderNo + "');\">递</a>");
                    // actions.push('<a href="javascript:void(0);" onclick="return vm.printEMS(' + options.rowId + ');">递</a>');
                    return actions.join('  ');
                }
            },
            {
                label: 'productionId',
                name: 'productionId',
                index: 'production_id',
                hidden: true,
                key: true,
                align: 'center'
            },
            {label: '订单号', name: 'orderNo', index: 'order_no', width: 100, align: 'center'},
            {label: '应付金额', name: 'payableAmount', index: 'payable_amount', width: 60, align: 'center'},
            {label: '产品名称', name: 'erpItemName', index: '', width: 120, align: 'center'},
            {label: '产品规格', name: 'addon', index: 'addon', width: 120, align: 'center'},
            {label: '数量', name: 'nums', index: 'nums', width: 40, align: 'center'},

            {label: '单位', name: 'unit', index: 'unit', width: 40, align: 'center'},
            {
                label: '生产状态',
                name: 'productionStatus',
                index: 'production_status',
                align: 'center',
                hidden: true,
                align: 'center'
            },
            {
                label: '生产状态', name: '', index: 'production_status', width: 50, align: 'center',
                formatter: function (value, options, row) {
                    var valueText = "";
                    var userData = $("#jqGrid").jqGrid('getGridParam', 'userData');
                    $.each(userData.orderProductionStatusEnum, function (index, module) {
                        if (module.id == row.productionStatus) {
                            valueText = module.describe;
                            return false;
                        }
                    });
                    return valueText;
                }
            },
            {label: '生产商', name: 'producerName', index: '', width: 100, align: 'center'},

            {label: '跟单员', name: 'pmcName', width: 50, align: 'center'},
            {label: '发货状态', name: 'shipStatus', width: 50, align: 'center',
                formatter: function (value, options, row) {
                    if(value == 0){
                        return "未发货"
                    }else if(value == 1){
                        return "已发货"
                    }else if(value == 2){
                        return "部分发货"
                    }else{
                        return value
                    }
                }
            },
            {label: '收货人', name: 'shipName', width: 100, align: 'center'},
            {label: '收货地区', name: 'shipArea', width: 100, align: 'center'},
            {label: '收货地址', name: 'shipAddr', width: 100},
            {label: '收货人手机', name: 'shipMobile', width: 100, align: 'center'},
            {label: '分配时间', name: 'allotTime', width: 100, align: 'center'},
            {label: '财务付款时间', name: 'financePaytime', width: 100, align: 'center'},
            {label: '生产备注', name: 'csRemark', index: 'csRemark', width: 100},
            {label: '客服备注', name: 'orRemarks', index: 'orRemarks', width: 100},
            {
                label: '图片', name: 'sendPicsUrl', index: '', width: 35, align: 'center',
                formatter: function (value, options, row) {
                    if (isBlank(value)) {
                        return '';
                    }
                    var urlArr = value.split(',');
                    var html = '<img class="img-thumbnail" src= "'+window.parent.vm.ossHost +urlArr[0]+'">';
                    return html;
                }
            }
        ],
        viewrecords: true,
        height: window.innerHeight - 120,
        rowNum: 25,
        rowList: [25, 50, 100],
        rownumbers: true,
        rownumWidth: 40,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            // 图片预览初始化
            $('.img-thumbnail').viewer();
            var userData = $("#jqGrid").jqGrid('getGridParam', 'userData');
            vm.e.orderProductionStatusEnum = userData.orderProductionStatusEnum;
        }
    });
    // 显示序号
    $("#jqGrid").jqGrid('setLabel', 0, '序号', '{width:80}');
});

var vm = new Vue({
        el: '#rrapp',
        data: {
            showList: true,
            showLogiNo: true,           // 是否显示配送单号
            showSendDetail: true,       // 是否显示发货明细
            EMSView: false,              //快递弹窗
            erpOrderProduction: {},
            erpOrder: {},
            sellerInfo: {},
            erpLogisticsEntity: {},      // 发货信息
            erpOrderItem: [],            // 订单明细
            logisticsItemList: [],      //勾选的订单明细
            q: {
                orderNo: '',
                productionStatus: '',
                shipStatus: '',
                beginAllotTime:'',
                endAllotTime:''
            },
            e: {
                orderProductionStatusEnum: [],
            },
            logisticsTypeList: [],
            /* 省市区data */
            area: [],
            radio: '1'
        },
        methods: {
            checkBeginDate: function () {
                WdatePicker({
                    dateFmt: 'yyyy-MM-dd HH:mm:ss', isShowClear: false, onpicking: function (dp) {
                        vm.q.beginAllotTime = dp.cal.getNewDateStr();
                    }
                })
            },
            checkEndDate: function () {
                WdatePicker({
                    dateFmt: 'yyyy-MM-dd HH:mm:ss', isShowClear: false, onpicking: function (dp) {
                        vm.q.endAllotTime = dp.cal.getNewDateStr();
                    }
                })
            },
            query: function () {
                vm.reload();
            },
            /* 查询重置 */
            reset: function () {
                vm.q.orderNo = '';
                vm.q.productionStatus = '';
                vm.q.shipStatus = '';
                vm.q.beginAllotTime = '';
                vm.q.endAllotTime = '';
                vm.reload();
            },
            print: function (rowId) {
                console.log(rowId)
            },
            send: function () {
                var that = this;
                var productionIds = getSelectedRows();
                if (productionIds == null) {
                    return;
                }
                $.ajax({
                    type: "GET",
                    url: baseURL + "production/erporderproduction/sendYangluoLogisticsInfo/" + productionIds,
                    contentType: "application/json",
                    data: null,
                    success: function (r) {
                        if (r.code == 0) {
                            vm.showList = false;
                            var areaData = r.area;
                            vm.area = JSON.parse(areaData);
                            vm.logisticsTypeList = r.logisticsTypeList;
                            vm.erpOrder = r.erpOrder;
                            vm.erpOrderItem = r.erpOrderItemEntityList;
                            that.$refs.multipleTable.toggleAllSelection();
                            vm.erpLogisticsEntity = {
                                toPeople: vm.erpOrder.shipName,
                                toPhone:  vm.erpOrder.shipMobile+""+(vm.erpOrder.shipTel == null?"":","+vm.erpOrder.shipTel),
                                toAddress: vm.erpOrder.shipAddr,
                                toArea: vm.erpOrder.shipArea,
                                toAreaId: vm.erpOrder.shipAreaId,
                                sendType: 3,
                                logiType: 2
                            };
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            },
            reload: function (event) {
                vm.showList = true;
                $("#jqGrid").jqGrid('setGridParam', {
                    page: 1,
                    postData: {
                        'orderNo': vm.q.orderNo,
                        'productionStatus': vm.q.productionStatus,
                        'shipStatus':vm.q.shipStatus,
                        'beginAllotTime':vm.q.beginAllotTime,
                        'endAllotTime':vm.q.endAllotTime
                    }
                }).trigger("reloadGrid");
            },
            reback: function () {
                vm.showList = true;
            },
            logiTypeChange: function (value) {
                for (var i = 0, logisticsType; logisticsType = vm.logisticsTypeList[i++];) {
                    // 紫云物流 不填写配送单号
                    if (logisticsType.logisticsId == value){
                        vm.erpLogisticsEntity.logiCompany = logisticsType.logisticsName;
                        if (logisticsType.logisticsName.indexOf("紫云-") == 0){
                            vm.showLogiNo = false;
                        }
                    }else {
                        vm.showLogiNo = true;
                    }
                }
            },
            sendTypeChange: function (value) {
                if (value == 1) {
                    vm.showSendDetail = false;
                } else {
                    vm.showSendDetail = true;
                }
            },
            handleItemChange: function (val) {
                var values = val.join(',').split(',');
                var areaId = values[val.length - 1];
                vm.erpLogisticsEntity.toAreaId = areaId;

                var lableObj = getCascaderObj(val, vm.area);
                var lable = lableObj.join(',').replace(new RegExp(',', 'g'), ' ');
                vm.erpLogisticsEntity.toArea = lable;
            },
            //监听订单明细勾选change事件
            // orderItemSelectionChange: function (value) {
            orderItemSelectionChange: function (row) {
                var list = new Array();
                for (var i = 0, orderItem; orderItem = row[i++];) {
                    var logisticsItem = {
                        orderItemId: orderItem.originalItemId,
                        orderItemName: orderItem.name,
                        quantity: orderItem.nums
                    }
                    list.push(logisticsItem);
                }
                vm.logisticsItemList = list;
            },
            // 参数验证
            validator: function () {
                if(vm.erpLogisticsEntity.logiType != 3){
                    if (isBlank(vm.erpLogisticsEntity.logisticsId)) {
                        alert("物流方式不能为空");
                        return false;
                    }
                }
                if (isBlank(vm.erpLogisticsEntity.toPeople)) {
                    alert("收货人不能为空");
                    return false;
                } else if (isBlank(vm.erpLogisticsEntity.toAreaId)) {
                    alert(" 收货地区不能为空");
                    return false;
                } else if (isBlank(vm.erpLogisticsEntity.toArea)) {
                    alert("收货地址不能为空");
                    return false;
                }
                return true;
            },
            // 添加物流信息保存
            saveLogistics: function () {
                // 验证参数
                if (!vm.validator()) {
                    return false;
                }
                var erpLogisticsDto = {
                    erpLogisticsEntity: vm.erpLogisticsEntity,
                    erpLogisticsItemList: vm.logisticsItemList
                }
                erpLogisticsDto.erpLogisticsEntity.orderNo = vm.erpOrder.orderNo;
                erpLogisticsDto.erpLogisticsEntity.sellerId = vm.erpOrder.thirdMerchantId;
                erpLogisticsDto.erpLogisticsEntity.orderId = vm.erpOrder.originalOrderId;
                erpLogisticsDto.erpLogisticsEntity.fromPeople = "ziyun";
                erpLogisticsDto.erpLogisticsEntity.fromArea = "湖北 武汉 江汉区";
                erpLogisticsDto.erpLogisticsEntity.fromAddress = "江汉区常青三路17B9-13";
                erpLogisticsDto.erpLogisticsEntity.fromPhone = "400-000-2519";
                console.log(erpLogisticsDto);
                $.ajax({
                    type: "POST",
                    url: baseURL + "logistics/erplogistics/saveYangluoLogisticsInfo",
                    contentType: "application/json",
                    data: JSON.stringify(erpLogisticsDto),
                    success: function (r) {
                        if (r.code === 0) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            },
            //弹出打印快递单
            showEMS(orderNo) {
                //获取收货人和发货人信息
                $.get(baseURL + "production/erporderproduction/expressFormInfo/" + orderNo, function (r) {
                    vm.erpOrder = r.erpOrder;
                    vm.sellerInfo = r.sellerInfo;
                    LODOP = getLodop();
                    LODOP.PRINT_INIT("");
                    vm.EMSView = true
                });
            },
            //打印快递单
            printEMS() {
                //初始化快递单
                LODOP = getLodop();
                LODOP.PRINT_INIT("初始化快递单");
                LODOP.SET_PRINT_PAGESIZE(1, 2200, 1200 , "");
                LODOP.SET_PRINT_STYLE("FontSize", 9);
                if (vm.radio == 1) {//韵达
                    LODOP.ADD_PRINT_TEXT(101, 110, 150, 25, vm.sellerInfo.sellerName);  //寄件人姓名
                    LODOP.ADD_PRINT_TEXT(101, 295, 150, 25, vm.sellerInfo.area);  //始发地城市
                    LODOP.ADD_PRINT_TEXT(126, 110, 302, 25, vm.sellerInfo.doorheadName);  //单位名称
                    LODOP.ADD_PRINT_TEXT(151, 110, 302, 25, vm.sellerInfo.addr);  //寄件地址1
                    LODOP.ADD_PRINT_TEXT(201, 110, 150, 25, vm.sellerInfo.sellerMobile); //联系电话1
                    LODOP.ADD_PRINT_TEXT(201, 254, 150, 25, vm.sellerInfo.shipZip);  //邮政编码1

                    LODOP.ADD_PRINT_TEXT(101, 470, 150, 25, vm.erpOrder.shipName);  //收件人姓名
                    LODOP.ADD_PRINT_TEXT(101, 645, 150, 25, vm.erpOrder.shipArea);  //目的地城市
                    LODOP.ADD_PRINT_TEXT(126, 470, 302, 25, vm.erpOrder.memberName);  //单位名称
                    LODOP.ADD_PRINT_TEXT(151, 470, 302, 25, vm.erpOrder.shipAddr);  //收件地址2
                    LODOP.ADD_PRINT_TEXT(201, 470, 150, 25, vm.erpOrder.shipMobile);  //联系电话2
                    LODOP.ADD_PRINT_TEXT(201, 596, 150, 25, vm.erpOrder.shipZip);  //邮政编码2
                }else if (vm.radio == 2) {//中通
                    LODOP.ADD_PRINT_TEXT(101, 110, 150, 25, vm.sellerInfo.sellerName);  //寄件人姓名
                    LODOP.ADD_PRINT_TEXT(101, 295, 150, 25, vm.sellerInfo.area);  //始发地城市
                    LODOP.ADD_PRINT_TEXT(126, 110, 302, 25, vm.sellerInfo.addr);  //寄件地址1
                    LODOP.ADD_PRINT_TEXT(151, 110, 302, 25, vm.sellerInfo.doorheadName );  //单位名称
                    LODOP.ADD_PRINT_TEXT(201, 110, 150, 25, vm.sellerInfo.sellerMobile); //联系电话1
                    LODOP.ADD_PRINT_TEXT(201, 254, 150, 25, vm.sellerInfo.shipZip);  //邮政编码1

                    LODOP.ADD_PRINT_TEXT(101, 470, 150, 25, vm.erpOrder.shipName);  //收件人姓名
                    LODOP.ADD_PRINT_TEXT(101, 645, 150, 25, vm.erpOrder.shipArea);  //目的地城市
                    LODOP.ADD_PRINT_TEXT(126, 470, 302, 25, vm.erpOrder.shipAddr);  //收件地址2
                    LODOP.ADD_PRINT_TEXT(151, 470, 302, 25, vm.erpOrder.memberName);  //单位名称
                    LODOP.ADD_PRINT_TEXT(201, 470, 150, 25, vm.erpOrder.shipMobile);  //联系电话2
                    LODOP.ADD_PRINT_TEXT(201, 596, 150, 25, vm.erpOrder.shipZip);  //邮政编码2
                }else if (vm.radio == 3) {//速尔
                    LODOP.ADD_PRINT_TEXT(101, 120, 150, 25, vm.sellerInfo.sellerName);  //寄件人
                    LODOP.ADD_PRINT_TEXT(101, 250, 150, 25, vm.sellerInfo.sellerMobile);//电话
                    LODOP.ADD_PRINT_TEXT(126, 120, 302, 25, vm.sellerInfo.doorheadName);  //寄件公司
                    LODOP.ADD_PRINT_TEXT(151, 120, 350, 50, vm.sellerInfo.area+vm.sellerInfo.addr);  //详细地址

                    LODOP.ADD_PRINT_TEXT(190, 120, 150, 25, vm.erpOrder.shipName);  //收件人
                    LODOP.ADD_PRINT_TEXT(190, 250, 150, 25, vm.erpOrder.shipMobile);  //电话
                    LODOP.ADD_PRINT_TEXT(215, 120, 302, 25, vm.erpOrder.memberName); //收件公司
                    LODOP.ADD_PRINT_TEXT(240, 120, 350, 50, vm.erpOrder.shipArea+vm.erpOrder.shipAddr);  //详细地址
                }
                LODOP.PRINT();
            },
            //初始化送货单
            createPrintPage: function () {
                LODOP = getLodop();
                LODOP.PRINT_INIT("Lodop初始化");
                LODOP.SET_PRINT_PAGESIZE(1, 2100, 1300, ""); //第一个参数为1表示纵向
                LODOP.ADD_PRINT_HTM(0, "3%", "95%", "100%", document.getElementById("printbox").innerHTML);
            },
            //打印送货单
            printGoods: function (orderNo) {
                $.get(baseURL + "order/erporder/info/" + orderNo, function (r) {
                    vm.erpOrder = r.erpOrder;
                    vm.erpOrderItem = r.erpOrderItemEntityList;
                    LODOP = getLodop();
                    LODOP.PRINT_INIT("");
                    layer.open({
                        type: 1,
                        skin: 'layui-layer-molv',
                        title: "打印送货单",
                        area: ['800px', '550px'],
                        shadeClose: false,
                        content: jQuery("#printGoods"),
                        btn: ['打印', '取消'],
                        btn1: function (index) {
                            vm.createPrintPage();
                            // LODOP.PRINT();
                            LODOP.PREVIEW();
                        }
                    });
                });
            },
            exportExcel() {
                //导出excel
                vm.q.orderNo = vm.q.orderNo.trim();
                const data = encodeURIComponent(JSON.stringify(vm.q));
                window.location.href = baseURL + "production/erporderproduction/exportExcel?postData=" + data;
            },
// createPrintPage: function () {
//     LODOP = getLodop();
//     LODOP.PRINT_INIT("初始化送货单");
//     LODOP.SET_PRINT_PAGESIZE(2,0,0,"A4");  //第一个参数为1表示纵向
//     LODOP.SET_PRINT_STYLE("FontSize",7);
//     LODOP.ADD_PRINT_TEXT(7, 418, 62, 29,"送货单");
//     LODOP.ADD_PRINT_TEXT(32, 36, 206, 25,"业务单号:" + vm.erpOrder.orderNo);
//     LODOP.ADD_PRINT_TEXT(32, 242, 191, 25, "客户名称:" + vm.erpOrder.shipName);
//     vm.erpOrder.merchantsSalesMan == null ? LODOP.ADD_PRINT_TEXT(32, 432, 148, 25, "业务员:") : LODOP.ADD_PRINT_TEXT(32, 432, 148, 25, "业务员:" + vm.erpOrder.orderNo.merchantsSalesMan);
//     LODOP.ADD_PRINT_TEXT(32, 580, 204, 25, "日期:" + vm.erpOrder.paymentTime);
//     LODOP.ADD_PRINT_TEXT(49, 36, 174, 25, "联系电话:" + vm.erpOrder.shipMobile);
//     LODOP.ADD_PRINT_TEXT(49, 211, 573, 25, "客户地址:" + vm.erpOrder.shipAddr);
//     LODOP.ADD_PRINT_TEXT(62, 57, 669, 25, "------------------------------------------------------------------------------------------------------------------------------------");
//     LODOP.ADD_PRINT_TEXT(73, 10, 33, 25, "序号");
//     LODOP.ADD_PRINT_TEXT(73, 44, 70, 25, "产品名称");
//     LODOP.ADD_PRINT_TEXT(73, 229, 42, 25, "规格");
//     LODOP.ADD_PRINT_TEXT(73, 467, 73, 25, "生产工艺");
//     LODOP.ADD_PRINT_TEXT(73, 571, 33, 25, "单位");
//     LODOP.ADD_PRINT_TEXT(73, 610, 34, 25, "数量");
//     LODOP.ADD_PRINT_TEXT(73, 644, 42, 25, "原价");
//     LODOP.ADD_PRINT_TEXT(73, 696, 39, 25, "现价");
//     LODOP.ADD_PRINT_TEXT(73, 740, 44, 25, "小计");
//     var a=0;
//     $(vm.erpOrderItem).each(function (i) {
//         a=i;
//         LODOP.ADD_PRINT_TEXT(89+i*9, 10, 33, 25, i + 1);
//         LODOP.ADD_PRINT_TEXT(89+i*9, 44, 185, 25, this.name);
//         LODOP.ADD_PRINT_TEXT(89+i*9, 229, 241, 25, this.addon);
//         LODOP.ADD_PRINT_TEXT(89+i*9, 468, 102, 25, this.craftsNames);
//         LODOP.ADD_PRINT_TEXT(89+i*9, 571, 38, 25, this.paperUnit);
//         LODOP.ADD_PRINT_TEXT(89+i*9, 610, 34, 25, this.nums);
//         LODOP.ADD_PRINT_TEXT(89+i*9, 644, 54, 25, this.price);
//         LODOP.ADD_PRINT_TEXT(89+i*9, 696, 55, 25, this.price);
//         LODOP.ADD_PRINT_TEXT(89+i*9, 740, 44, 25, this.amount);
//
//     });
//     LODOP.ADD_PRINT_TEXT(239, 10, 96, 25, "运费:"+vm.erpOrder.costFreight);
//     LODOP.ADD_PRINT_TEXT(239, 107, 129, 25, "订单减免:"+vm.erpOrder.discount);
//     LODOP.ADD_PRINT_TEXT(239, 237, 298, 25, "合计(大写):" + smalltoBIG(vm.erpOrder.payableAmount));
//     vm.erpOrder.sendTax == 1 ?LODOP.ADD_PRINT_TEXT(239, 535, 155, 255, "备注:带发票"):LODOP.ADD_PRINT_TEXT(239, 535, 155, 25, "备注:不带发票");
//     LODOP.ADD_PRINT_TEXT(257, 10, 230, 25, "送货人:");
//     LODOP.ADD_PRINT_TEXT(257, 237, 270, 25, "客户签章:");
//
// }
        },
    })
;

/**
 * 省市区级联选择
 * @param val
 * @param opt
 */
function getCascaderObj(val, opt) {
    return val.map(function (value, index, array) {
        for (var itm in opt) {
            if (opt[itm].value == value) {
                var label = opt[itm].label;
                opt = opt[itm].children;
                return label;
            }
        }
        return null;
    });
}

/** 数字金额大写转换(可以处理整数,小数,负数) */
function smalltoBIG(n) {
    var fraction = ['角', '分'];
    var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    var unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
    var head = n < 0 ? '欠' : '';
    n = Math.abs(n);

    var s = '';

    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    n = Math.floor(n);

    for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
    }
    return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}